<!--
 * 二次封装带模糊搜索的select控件
 * @param value  需要绑定的值
 * @param options  需要循环的数组 必传
 * @param el-option参数 必传
 * @example  <nr-select v-model="value" :options="list" :props="{label: 'name', value: 'id'}"  placeholder="请选择客户编号" />
 * @returns {*}
-->
<template>
  <el-select ref="optionRef"
             :value="value"
             v-bind="$attrs"
             :placeholder="$attrs.placeholder"
             :filter-method="handleFilter"
             filterable
             clearable
             size="small"
             v-on="$listeners"
             @focus="clearSelect"
             @clear="clearSelect">
    <el-option v-for="item in optionsList"
               :key="item[props.value]"
               v-bind="$attrs"
               :disabled="item.disabled"
               :label="item[props.label]"
               :value="item[props.value]">
      <el-tooltip v-if="item.disabled"
                  effect="dark"
                  :content="item.text"
                  placement="bottom">
        <span>{{ item[props.label] }}</span>
      </el-tooltip>
    </el-option>
  </el-select>
</template>

<script>
import PinyinMatch from "pinyin-match";
export default {
  name: "SearchSelect",
  model: {
    prop: "value",
    event: "input"
  },
  props: {
    // 需要绑定的值 等于 v-model
    value: {
      type: [String, Number],
      default: null
    },
    // 需要循环的数组 必传
    options: {
      type: Array,
      default: () => [],
      required: true
    },
    // el-option参数 必传
    props: {
      type: Object,
      default () {
        return {
          value: "value",
          label: "label"
        };
      },
      required: true
    }
  },
  data () {
    return {
      optionsList: [],
      copyOptionsList: []
    };
  },
  watch: {
    // 监听赋值并copy一份
    options (val) {
      if (val) {
        this.optionsList = val;
        this.copyOptionsList = JSON.parse(JSON.stringify(val));
      }
    }
  },
  mounted () {
    this.optionsList = this.options;
    this.copyOptionsList = JSON.parse(JSON.stringify(this.options));
  },
  methods: {
    // 下拉框支持模糊搜索
    handleFilter (val) {
      try {
        if (val) {
          this.optionsList = this.copyOptionsList;
          this.optionsList = this.optionsList.filter((item) =>
            PinyinMatch.match(item[this.props.label], val)
          );
        } else {
          this.optionsList = this.copyOptionsList;
        }
      } catch (error) {
        console.error("模糊下拉框：", error);
      }
    },
    // clear、focus事件还原数组
    clearSelect () {
      this.optionsList = this.copyOptionsList;
    }
  }
};
</script>
